/*
 * Copyright (c) 2016. 恒昌互联网运营中心.
 */
package com.credithc.eagleeye.agent.strategy;
import com.alibaba.fastjson.JSON;
import com.credithc.eagleeye.agent.bean.EagleEyeAgentConfig;
import com.credithc.eagleeye.vo.RpcTraceInfoVo;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.atomic.AtomicBoolean;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2016年09月26日<br/>
 * 版 本：v1.0.0<br>
 * <p/>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
public class RedisEagleEyeAgent extends  AbsEagleEyeAgent {
    private transient static final Logger logger = LoggerFactory.getLogger(RedisEagleEyeAgent.class);
    private final static String EAGLE_EYE_REDIS_LIST_KEY = "eagle_eye_info_list";
    private volatile JedisPool jedisPool;
    private static AtomicBoolean initialized = new AtomicBoolean(false);
    public RedisEagleEyeAgent(EagleEyeAgentConfig eagleEyeAgentConfig) {
        super(eagleEyeAgentConfig);
        init();
    }
    private void init() {
        if( initialized.compareAndSet(false, true) ){
            logger.info("RedisEagleEyeAgent init starting...");
            String address = eagleEyeAgentConfig.getRedisAddress();
            if (address == null || address.length() == 0) {
                throw new RuntimeException("RedisEagleEyeAgent error:redis config address is blank!");
            }
            GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
            genericObjectPoolConfig.setMaxWaitMillis(eagleEyeAgentConfig.getRedisMaxWaitMillis());
            genericObjectPoolConfig.setMaxTotal(eagleEyeAgentConfig.getRedisMaxTotal());
            genericObjectPoolConfig.setMinIdle(eagleEyeAgentConfig.getRedisMinIdle());
            genericObjectPoolConfig.setMaxIdle(eagleEyeAgentConfig.getRedisMaxIdle());
            String[] ipAndPort = address.trim().split(":");
            String ip = ipAndPort[0].trim();
            int port = Integer.parseInt(ipAndPort[1].trim());
            jedisPool=new JedisPool(genericObjectPoolConfig, ip, port, eagleEyeAgentConfig.getRedisTimeout());
            logger.info("RedisEagleEyeAgent init finished,address:"+address);
        }
    }

    @Override
    public boolean doSend2EagleEye(final RpcTraceInfoVo rpcTraceInfoVo) {
        Jedis jedis = getResource();
        try {
            jedis.rpush(EAGLE_EYE_REDIS_LIST_KEY, JSON.toJSONString(rpcTraceInfoVo));
            logger.debug(String.format("send to eagleEye redis traceId:%s,rpcId:%s",rpcTraceInfoVo.getTraceId(),rpcTraceInfoVo.getRpcId()));
            return true;
        }catch(Exception ex){
            logger.error(String.format("redis方式发送鹰眼系统error:"+ex.getMessage()));
        } finally{
            jedis.close();
        }
        return false;
    }

    /**
     * <br>描 述：获取资源
     * <br>历 史: (版本) 作者 时间 注释
     *
     * @return
     */
    private Jedis getResource() {
        if (jedisPool == null) {
            throw new RuntimeException("eagle-redis配置未初始化");
        }
        Jedis jedis = this.jedisPool.getResource();
        return jedis;
    }
}
